import { provinces } from '../data/province.js'
import { citys } from '../data/city.js'
import { countys } from '../data/county.js'
import { towns } from '../data/town.js'
// fs
import { writeFile } from 'fs/promises';

/* 生成 targetID */
const handlerTargetFn = (objAndArr, index = 0, regexLimit = 2) => {
  if (!objAndArr) return null
  const regExp = new RegExp(`.{1,${regexLimit}}`, 'g')
  if (Object.prototype.toString.call(objAndArr) === '[object Array]') {
    return objAndArr.map(im => ({
      // ...im,
      id: im['id'],
      value: im['id'].match(regExp)[index],
      // value: `${im['name']}-${im['id']}`,
      // value: im['id'],
      label: im['name'],
      // targetID: im['id'].match(regExp)[index]
    }))
  }
  if (Object.prototype.toString.call(objAndArr) === '[object Object]') {
    const newObj = {}
    for (const key in objAndArr) {
      if (Object.prototype.hasOwnProperty.call(objAndArr, key)) {
        const element = handlerTargetFn(objAndArr[key], index, regexLimit)
        newObj[key] = element
      }
    }
    return newObj
  }
  return null
}
// 省/直辖市
const provinceList = handlerTargetFn(provinces, 0)
// 市
const cityObj = handlerTargetFn(citys, 0, 4)
// 区
const countyObj = handlerTargetFn(countys, 0, 6)
// 镇
const townsObj = handlerTargetFn(towns, 0, 12)

/* 省/直辖市 => 市 */
export const provinceCityFn = () => JSON.parse(JSON.stringify(provinceList.map(im => ({
  ...im,
  children: (new Map(Object.entries(cityObj))).get(im.id) || []
}))))
// console.log(provinceCity[1]);

/* 省/直辖市 => 市 => 区 */
export const provinceCityCountyFn = () => JSON.parse(JSON.stringify(provinceCityFn().map(im => {
  const curr = im
  curr['children'].forEach(imm => {
    imm['children'] = (new Map(Object.entries(countyObj))).get(imm.id) || []
  })
  return curr
})))
// console.log(provinceCityCounty[0]['children'][0]);

/* 省/直辖市 => 市 => 镇 */
export const provinceCityCountyTownFn = () => JSON.parse(JSON.stringify(provinceCityCountyFn().map(im => {
  const curr = im
  curr['children'].forEach(imm => {
    const curr = imm
    curr['children'].forEach(immm => {
      immm['children'] = (new Map(Object.entries(townsObj))).get(immm.id) || []
    })
  })
  return curr
})))
// console.log(provinceCityCountyTown[0]['children'][0]['children'][0]);


/* 把数据写入到当前项目当中, output.json  */
const writeJsonFileFn = (fileName = 'output.json', obj = provinceCityCountyTownFn()) => {
  // 将对象转换为 JSON 字符串，指定缩进 4 格，格式化输出更易读
  const jsonString = JSON.stringify(cxc(obj), null, 0);

  async function writeJsonFile(filePath, data) {
    try {
      // 使用 fs.promises 的 writeFile 方法进行文件写入
      await writeFile(filePath, data, 'utf8');
      console.log('文件写入成功');
    } catch (err) {
      console.error('写入文件时发生错误:', err);
    }
  }

  // 调用写入函数，将深层嵌套的对象写入到 'output.json' 中
  writeJsonFile(fileName, jsonString);
}

// 删除掉 id 属性
function cxc(obj) {
  return obj.map(i => {
    delete i['id'];
    if (i['children'] && i['children'].length) {
      i['children'] = cxc(i['children'])
    }
    return i
  })
}

writeJsonFileFn('../data/my-pcas.json')